package com.mvc.web.common.base;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSONObject;
import com.mvc.web.common.utils.AESUtil;
import com.mvc.web.common.utils.DomainUtils;
import com.mvc.web.common.utils.MailUtil;
import com.mvc.web.common.utils.ToolsUtils;

public class BaseController {

    protected Logger logger;

    protected HttpServletRequest request;  
    protected HttpSession session;  
    protected long requestId;
    protected String ip;
    protected String uri;
      
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){  
    	this.request = request;
        this.session = request.getSession();
        
        //获取请求的id
        if(ToolsUtils.isNotEmpty(request.getHeader("X-Qmc-Logid32"))){
        	this.requestId  = Long.parseLong(request.getHeader("X-Qmc-Logid32"));
        }else{
        	this.requestId  = System.currentTimeMillis();
        }
        
        //获取ip
        if(ToolsUtils.isNotEmpty(request.getHeader("X-Real-Ip"))){
        	ip  = request.getHeader("X-Real-Ip");
        }
        this.uri = request.getContextPath()+request.getServletPath();
        
    } 
    
    public BaseController() {
        logger = Logger.getLogger(this.getClass().getName());
    }
    
    public String Error(String msg,Exception e){
    	JSONObject res = new JSONObject();
    	if(e!=null){
	    	e.printStackTrace();
			StringWriter sw = new StringWriter();   
	        e.printStackTrace(new PrintWriter(sw, true));   
	        logger.error("request_id:"+requestId+" detail: "+sw.toString(), e);
	        String tempContextUrl = DomainUtils.getDomain(request.getRequestURL()==null?"":request.getRequestURL().toString());
	        if(ToolsUtils.isNotEmpty(tempContextUrl)&&tempContextUrl.contains("com")){
	        	Enumeration<String> enu=request.getParameterNames();  
	        	String param = "params--> ";
	        	if(enu!=null){
	        		while(enu.hasMoreElements()){  
	        			String paraName=(String)enu.nextElement();  
	        			param+=paraName + ":"+request.getParameter(paraName)+"<br>";
	        		}
	        	}
	        	String local_url =request.getServletPath();
	        	String requestid = request.getHeader("X-Qmc-Logid32");
	        	String ctype = request.getHeader("ctype");
	        	if (ToolsUtils.isEmpty(requestid)) {
	        		requestid = System.currentTimeMillis() + "";
	        	}
	        	String str = " domain:"+tempContextUrl+" ctype:"+ctype+" requestId:"+requestid+" IP:"+ToolsUtils.getRealIP(request)+" API:"+local_url+"<br>";
	        	MailUtil mu = new MailUtil("货运巴巴异常", str+sw.toString()+"<br>"+param, "baihaian@126.com", null);
	        	mu.sendEmail();
        	}
        }
    	res.put("errorCode", 500);
    	res.put("errorMsg", "服务器异常，请稍后重试");
    	res.put("requestId", requestId);
		return res.toString();
    }
    
    public String Success(){
    	JSONObject res = new JSONObject();
    	res.put("errorCode", 0);
    	res.put("errorMsg", "success");
    	res.put("requestId", requestId);
    	return res.toString();
    }
    
    /** 
     * @Description: 从cookie中读出数ID属性的值 
     * @author baihaian(baiha@jizhicar.com) 2017年5月12日 下午3:03:06
     * @param request
     * @param name
     * @return
     * @version V1.5.5
     */
    public int getIdFormCookie(HttpServletRequest request,String name) {
    	Cookie[] cookies = request.getCookies();
        if(cookies != null){
        	for(Cookie c :cookies ){
        		if(name.equals(c.getName())){
        			try {
        				return Integer.parseInt(AESUtil.base64AESDecrypt(c.getValue()));
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
        		}
        	}
        }else{
        	return 0;
        }
		return 0;
    }
    
    /** 
     * @Description: 从cookie中读取出值 
     * @author baihaian(baiha@jizhicar.com) 2017年5月12日 下午3:03:50
     * @param request
     * @param name
     * @return
     * @version V1.5.5
     */
    public String getValueFormCookie(HttpServletRequest request,String name) {
    	Cookie[] cookies = request.getCookies();
    	if(cookies != null){
    		for(Cookie c :cookies ){
    			if(name.equals(c.getName())){
    				try {
    					return AESUtil.base64AESDecrypt(c.getValue());
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}else{
    		return "";
    	}
    	return "";
    }
}
